import { useEffect, useState } from "react";
import { Button, Card, Form, Input } from "antd";
import type { ColumnsType } from "antd/es/table";
import stockService, {
  type PageListReq,
} from "@/api/services/wms/stockService";
import type { WmsStockRecord } from "./entity";
import { toast } from "sonner";
import CustomTable from "@/components/grid/CustomTable";

export default function WmsStockRecordPage() {
  const [loading, setLoading] = useState(false);
  const [queryParams, setQueryParams] = useState<PageListReq>({
    type: undefined,
    operateType: undefined,
    materialId: undefined,
    batchCode: undefined,
    warehouseId: undefined,
    locationId: undefined,
    areaId: undefined,
    page: 1,
    pageSize: 10,
  });
  const [total, setTotal] = useState(0);
  const [list, setList] = useState<WmsStockRecord[]>([]);

  //动态设置表格高度
  const [tableScrollY, setTableScrollY] = useState(0);
  const PAGE_OFFSET_HEIGHT = 405;
  const updateTableHeight = () => {
    const newHeight = window.innerHeight - PAGE_OFFSET_HEIGHT;
    setTableScrollY(newHeight > 200 ? newHeight : 200); // 保证最小高度
  };

  useEffect(() => {
    updateTableHeight(); // 初始化
    window.addEventListener("resize", updateTableHeight);
    return () => window.removeEventListener("resize", updateTableHeight);
  }, []);

  const columns: ColumnsType<WmsStockRecord> = [
    {
      title: "类型",
      width: 120,
      key: "type",
      dataIndex: "type",
    },
    {
      title: "操作类型",
      width: 120,
      key: "operateType",
      dataIndex: "operateType",
    },
    {
      title: "产品物料ID",
      width: 120,
      key: "materialId",
      dataIndex: "materialId",
    },
    {
      title: "批次号",
      width: 120,
      key: "batchCode",
      dataIndex: "batchCode",
    },
    {
      title: "仓库ID",
      width: 120,
      key: "warehouseId",
      dataIndex: "warehouseId",
    },
    {
      title: "库区ID",
      width: 120,
      key: "locationId",
      dataIndex: "locationId",
    },
    {
      title: "库位ID",
      width: 120,
      key: "areaId",
      dataIndex: "areaId",
    },
    {
      title: "数量",
      width: 120,
      key: "qty",
      dataIndex: "qty",
    },
    {
      title: "关联单据号",
      width: 120,
      key: "relateOrderCode",
      dataIndex: "relateOrderCode",
    },
    {
      title: "备注",
      width: 120,
      key: "remark",
      dataIndex: "remark",
    },
  ];

  //加载表格数据
  const fetchPageList = () => {
    setLoading(true);
    stockService
      .recordPageList(queryParams)
      .then((res) => {
        setList(res.records);
        setTotal(res.total);
      })
      .catch((error) => {
        console.log(error);
        toast.error("获取数据失败！", error);
      })
      .finally(() => {
        setLoading(false);
      });
  };

  // biome-ignore lint/correctness/useExhaustiveDependencies: <explanation>
  useEffect(() => {
    fetchPageList();
  }, [queryParams]);

  //选择其他页
  const handlePageChange = (newPage: number, newPageSize: number) => {
    setQueryParams((prev) => ({
      ...prev,
      page: newPage,
      pageSize: newPageSize,
    }));
  };

  return (
    <Spin spinning={submitLoading} tip="数据提交中..." size="large">
      <Card className="mb-4">
        <Form
          layout="inline"
          onFinish={(values) => {
            setQueryParams((prev) => ({
              ...prev,
              ...values,
              page: 1,
            }));
          }}
        >
          <Form.Item name="type" label="类型">
            <Input placeholder="请输入类型" allowClear />
          </Form.Item>
          <Form.Item name="operateType" label="操作类型">
            <Input placeholder="请输入操作类型" allowClear />
          </Form.Item>
          <Form.Item name="materialId" label="产品物料ID">
            <Input placeholder="请输入产品物料ID" allowClear />
          </Form.Item>
          <Form.Item name="batchCode" label="批次号">
            <Input placeholder="请输入批次号" allowClear />
          </Form.Item>
          <Form.Item name="warehouseId" label="仓库ID">
            <Input placeholder="请输入仓库ID" allowClear />
          </Form.Item>
          <Form.Item name="locationId" label="库区ID">
            <Input placeholder="请输入库区ID" allowClear />
          </Form.Item>
          <Form.Item name="areaId" label="库位ID">
            <Input placeholder="请输入库位ID" allowClear />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              查询
            </Button>
            <Button
              className="ml-2"
              onClick={() => {
                setQueryParams({ page: 1, pageSize: 10 });
              }}
            >
              重置
            </Button>
          </Form.Item>
        </Form>
      </Card>
      <div className="h-4" />
      <Card>
        <CustomTable
          loading={loading}
          columnsConfig={columns}
          dataSource={list}
          selectedRowKeys={selectedRowKeys}
          setSelectedRowKeys={setSelectedRowKeys}
          total={total}
          current={queryParams.page}
          pageSize={queryParams.pageSize}
          onPageChange={handlePageChange}
          onRefresh={fetchPageList}
          selectable
          toolbarButtons={
            <>
              <Button type="primary" onClick={handleAdd}>
                新增
              </Button>
              <Button
                danger
                disabled={selectedRowKeys.length === 0}
                onClick={handleDelete}
              >
                删除
              </Button>
            </>
          }
          scroll={{ y: tableScrollY }}
        />
      </Card>
    </Spin>
  );
}
